package com.suep.file.service.impl;

import com.suep.file.service.IFileService;
import com.suep.file.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.juli.logging.Log;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@Service
public class FileServiceImpl implements IFileService {
    @Value("${file.upload-path}")
    private String uploadDir;

    @Value("${custom.location}")
    private String location;


    /*
    * 返回服务器完整路径
    * */
    @Override
    public String  saveFile(MultipartFile file, Integer userId) throws IOException {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传文件不能为空");
        }
        // 生成安全文件名
        String originalFileName = file.getOriginalFilename();
        String safeFileName = FileUtil.generateUniqueFileName(originalFileName);

        // 构建用户专属存储路径
        Path userDir = Paths.get(uploadDir, "user_" + userId)
                .toAbsolutePath()
                .normalize();
        // 新增目录存在性校验,目录不存在则创建
        if (!Files.exists(userDir)) {
            log.info("为用户 {} 创建存储目录：{}", userId, userDir);
            try {
                Files.createDirectories(userDir);
            } catch (FileAlreadyExistsException e) {
                // 处理极端并发情况
                log.warn("目录已被其他线程创建：{}", userDir);
            }
        }
        // 完整存储路径
        Path targetPath = userDir.resolve(safeFileName);
        // 保存文件
        file.transferTo(targetPath);

        //输出结果路径
        return location+userId+"/"+safeFileName;
    }



    /*
    * 下载文件*/
    @Override
    public Resource downloadFile(String fileName) throws MalformedURLException, FileNotFoundException {

        // 确保文件名合法
        if (fileName == null || fileName.isEmpty()) {
            throw new IllegalArgumentException("文件名不能为空");
        }

        Path uploadPath = Paths.get(uploadDir).toAbsolutePath().normalize();
        Path filePath = uploadPath.resolve(FileUtil.sanitizeFileName(fileName)).normalize();

        // 安全校验：确保路径在允许的目录内
        if (!filePath.startsWith(uploadPath)) {
            throw new SecurityException("非法文件路径访问");
        }

        Resource resource = new UrlResource(filePath.toUri());
        if (resource.exists() && resource.isReadable()) {
            return resource;
        } else {
            throw new FileNotFoundException("文件不存在或不可读");
        }
    }

    /*
    * 加载文件*/
    @Override
    public Resource loadFile(String fileUrl) throws MalformedURLException, FileNotFoundException {
        // 确保文件名合法
        if (fileUrl == null || fileUrl.isEmpty()) {
            throw new IllegalArgumentException("文件名不能为空");
        }
        Path uploadPath = Paths.get(uploadDir).toAbsolutePath().normalize();
        System.out.println("实际上传的根目录配置"+uploadPath);

//        /user_1/20250427_223402___________-__-__.png
        String[] pathSegments = fileUrl.split("/", 3);  // 拆分为最多3段
        if (pathSegments.length < 2 || !pathSegments[1].startsWith("user_")) {
            throw new IllegalArgumentException("无效路径格式");
        }
        String userDir=pathSegments[1];
        String fileName = pathSegments[2];
        Path filePath = Paths.get(uploadDir, userDir, fileName).toAbsolutePath().normalize();
        System.out.println("处理后的文件路径"+filePath);

        // 安全校验：确保路径在允许的目录内
        if (!filePath.startsWith(uploadPath)) {
            throw new SecurityException("非法文件路径访问");
        }
        Resource resource = new UrlResource(filePath.toUri());
        System.out.println("实际加载的文件路径"+filePath.toUri());
        if (resource.exists() && resource.isReadable()) {
            return resource;
        } else {
            throw new FileNotFoundException("文件不存在或不可读");
        }
    }

}
